﻿using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using UnityEngine;

public class SerizlizerDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        return null;
    }

    //序序列化
    public void ReadXml(XmlReader reader)
    {
        XmlSerializer KeySer = new XmlSerializer(typeof(TKey));
        XmlSerializer ValSer = new XmlSerializer(typeof(TValue));
        //跳过根节点
        reader.Read();

        while (reader.NodeType != XmlNodeType.EndElement)
        {
            TKey key = (TKey)KeySer.Deserialize(reader);
            TValue value = (TValue)ValSer.Deserialize(reader);
            this.Add(key, value);
        }
    }

    //序列化
    public void WriteXml(XmlWriter writer)
    {
        XmlSerializer KeySer = new XmlSerializer(typeof(TKey));
        XmlSerializer ValSer = new XmlSerializer(typeof(TValue));
        foreach (KeyValuePair<TKey, TValue> kv in this)
        {
            KeySer.Serialize(writer, kv.Key);
            ValSer.Serialize(writer, kv.Value);
        }
    }
}
